package io.gitee.chearnee.fw.openapi.advice;

import io.gitee.chearnee.fw.openapi.annotation.AuthValidate;
import io.gitee.chearnee.fw.openapi.constant.OpenApiContextHolder;
import io.gitee.chearnee.fw.openapi.model.AuthParam;
import io.gitee.chearnee.fw.openapi.processor.PreProcessor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author cn
 * @version 1.0
 * @date 2021/5/24 18:44
 */
@Aspect
@Component
@Slf4j
@RequiredArgsConstructor
public class AuthValidateAdvice {

  private final PreProcessor preProcessor;

  @Before("@annotation(authValidate)")
  public void validate(JoinPoint joinPoint, AuthValidate authValidate) {
    Object[] args = joinPoint.getArgs();
    String appId = OpenApiContextHolder.getOpenApiContext().getAppId();

    List<AuthParam> authParam = preProcessor.getAuthResource(appId, args);
    if (!authParam.isEmpty()) {
      preProcessor.checkAuthResource(authParam);
    }
  }
}
